package cn.gson.zuche.tag;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import cn.gson.zuche.common.StringUtils;



public class FYpageTag extends SimpleTagSupport{

	private String url;
	private String page;
	private String totlepage;
	private String suoyoujilu;
	@Override
	public void doTag() throws JspException, IOException {	
		StringBuffer sb = new StringBuffer("<div class=\"page\">");
		String zfc=this.getParamStr();	
		if (Integer.parseInt(page)==1) {
			sb.append("<a class=\"disable\">首页</a>&nbsp&nbsp&nbsp");
			sb.append(" <a class=\"disable\">上一页</a>&nbsp&nbsp&nbsp");
		} else {
			sb.append("<a href=\"" + url + "?page=1"+zfc+"\">首页</a>&nbsp&nbsp&nbsp");
			sb.append("<a href=\"" + url + "?page="+(Integer.parseInt(page)-1)+""+zfc+"\">上一页</a>&nbsp&nbsp&nbsp");
		}
		if (Integer.parseInt(page)==Integer.parseInt(totlepage)) {
			sb.append("<a class=\"disable\">下一页</a>&nbsp&nbsp&nbsp");
			sb.append("<a class=\"disable\">尾页</a>&nbsp&nbsp&nbsp");
		} else {
			sb.append("<a href=\"" + url + "?page=" + (Integer.parseInt(page)+ 1) +""+zfc+"\">下一页</a>&nbsp&nbsp&nbsp");
			sb.append("<a href=\"" + url + "?page=" + totlepage + ""+zfc+"\">尾页</a>&nbsp&nbsp&nbsp");
		}
		sb.append(String.format("%s/%s(共有%s条)", page, totlepage,suoyoujilu));
		sb.append("</div>");
		getJspContext().getOut().write(sb.toString());
	}
	public String getParamStr() throws UnsupportedEncodingException {
		PageContext pageContext = (PageContext) this.getJspContext();
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		Enumeration<String> pnames = request.getParameterNames();
		List<String> params = new ArrayList<>();
		while (pnames.hasMoreElements()) {
			String name = (String) pnames.nextElement();
			if (!"page".equalsIgnoreCase(name)) {
				String[] values = request.getParameterValues(name);
				for (String value : values) {
					if (!StringUtils.isEmpty(value)) {						
						params.add(name + "=" + URLEncoder.encode(value,"UTF-8"));
					}
				}
			}
		}
		StringBuffer sb = new StringBuffer();
		if (params.size() > 0) {
			sb.append("&");
			for (String item : params) {
				sb.append(item).append("&");		
			}
			sb.deleteCharAt(sb.length() - 1);
		}
		return sb.toString();
	}
	public void setsuoyoujilu(String suoyoujilu){
		this.suoyoujilu=suoyoujilu;
	}
	public void seturl(String url){
		this.url=url;
	}
	public void setpage(String page){
		this.page=page;
	}
	public void settotlepage(String totlepage){
		this.totlepage=totlepage;
	}
}
